package io.xccit.web.controller.common;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.xccit.common.utils.MinIOUtils;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import io.xccit.common.utils.uuid.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.xccit.common.config.RaceConfig;
import io.xccit.common.core.domain.AjaxResult;
import io.xccit.common.utils.StringUtils;
import io.xccit.common.utils.file.FileUploadUtils;
import io.xccit.common.utils.file.FileUtils;
import io.xccit.framework.config.ServerConfig;

/**
 * 通用请求处理
 * 
 * @author ywx
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private MinIOUtils minIOUtils;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RaceConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RaceConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RaceConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RaceConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + FileUtils.stripPrefix(resource);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * minio上传单个文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/minio/upload")
    public AjaxResult minioUploadFile(MultipartFile file) throws Exception {
        String url = minIOUtils.upload(file);
        String fileName = FileUtils.getName(file.getOriginalFilename());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        return ajax;
    }

    /**
     * 上传多个文件到Minio并获取相关文件名
     * 该接口用于将多个文件上传到Minio存储，并返回上传后的URL、原始文件名以及新生成的文件名。
     *
     * @param files 要上传的文件列表
     * @return 包含上传后的URL、原始文件名以及新生成的文件名的AjaxResult对象
     * @throws Exception 上传过程中发生异常时抛出
     */
    @PostMapping("/minio/uploads")
    public AjaxResult minioUploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                String url = minIOUtils.upload(file);
                urls.add(url);
                fileNames.add(file.getOriginalFilename());
                newFileNames.add(FileUtils.getName(url));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 列出所有存储桶
     */
    @GetMapping("/minio/buckets")
    public AjaxResult listBuckets() throws Exception {
        List<Bucket> buckets = minIOUtils.listBuckets();
        return AjaxResult.success(buckets);
    }

    /**
     * 创建存储桶
     */
    @PostMapping("/minio/bucket")
    public AjaxResult createBucket(@RequestParam("bucket") String bucket) throws Exception {
        if (minIOUtils.existBucket(bucket)) {
            return AjaxResult.error("存储桶已存在");
        }
        minIOUtils.makeBucket(bucket);
        return AjaxResult.success();
    }

    /**
     * 删除存储桶（需为空）
     */
    @DeleteMapping("/minio/bucket/{bucket}")
    public AjaxResult deleteBucket(@PathVariable("bucket") String bucket) throws Exception {
        minIOUtils.removeBucket(bucket);
        return AjaxResult.success();
    }

    /**
     * 列出桶内对象
     */
    @GetMapping("/minio/objects")
    public AjaxResult listObjects(@RequestParam("bucket") String bucket,
                                  @RequestParam(value = "prefix", required = false) String prefix,
                                  @RequestParam(value = "recursive", required = false, defaultValue = "true") boolean recursive) throws Exception {
        List<Item> items = minIOUtils.listObjects(bucket, prefix, recursive);
        return AjaxResult.success(items);
    }

    /**
     * 删除对象
     */
    @DeleteMapping("/minio/object")
    public AjaxResult deleteObject(@RequestParam("bucket") String bucket,
                                   @RequestParam("object") String object) throws Exception {
        boolean ok = minIOUtils.removeObject(bucket, object);
        return ok ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    /**
     * 获取预签名URL
     */
    @GetMapping("/minio/presign")
    public AjaxResult getPresign(@RequestParam("bucket") String bucket,
                                 @RequestParam("object") String object,
                                 @RequestParam(value = "expires", required = false, defaultValue = "3600") int expires) throws Exception {
        String url = minIOUtils.getPresignedUrl(bucket, object, expires);
        return AjaxResult.success(url);
    }
}
